#include <stdio.h>
#include "cgic.h"
#include <string.h>
#include <stdlib.h>
#include <glib.h>
#include "msgUtils.h"

int cgiMain() {
    //接收到的数据
    char gatewayIp[128];
    char location[128];

    //获取前端返回的post请求数据
    cgiFormString("gatewayIp",gatewayIp,128);
    cgiFormString("location",location,128);

    //将获取到的数据存放进入config文件
    GKeyFile* keyFile = g_key_file_new();//用于读取文件

    //在这里可以使用config.ini来存储真正的配置文件地址
    //这样可以方便移植
    //链接存放地址的配置文件，读取真正配置文件（存放前端请求的数据文件的地址）地址
    if(!g_key_file_load_from_file(keyFile,"./config.ini",G_KEY_FILE_NONE,NULL)){
        g_warning("load config.ini error!");
        return -1;
    }
    //读取信息
    gchar* data = g_key_file_get_string(keyFile,"config","devPath",NULL);

    GKeyFile* devFile = g_key_file_new();//用于存放数据

    //设置信息
    g_key_file_set_string(devFile,"config","gatewayIp",gatewayIp);
    g_key_file_set_string(devFile,"config","location",location);
    g_key_file_save_to_file(devFile,data,NULL);
    g_key_file_free(keyFile);
    g_key_file_free(devFile);

    //发送消息给心跳进程
    message msg={
        .type = 1,
        .content = "hello"
    };
    //获取mqid
    int mqId = getMqId();
    //发送消息
    int res = sendMsg(mqId,&msg);
    if (res == -1)
    {
    cgiHeaderContentType("text/html");
	/* Top of the page */
	fprintf(cgiOut, "<HTML><HEAD>\n");
	fprintf(cgiOut, "<TITLE>cgic test</TITLE></HEAD>\n");
	fprintf(cgiOut, "<BODY><H1>msg send failed!</H1>\n");
    fprintf(cgiOut, "</BODY></HTML>\n");
    }
    
    cgiHeaderContentType("text/html");
	/* Top of the page */
	fprintf(cgiOut, "<HTML><HEAD>\n");
	fprintf(cgiOut, "<TITLE>cgic test</TITLE></HEAD>\n");
	fprintf(cgiOut, "<BODY><H1>suceess!</H1>\n");
    fprintf(cgiOut, "</BODY></HTML>\n");
    return 0;
}